<template>
	<view class="device">
		<view class="member-list">
			<block v-for="(val, index) in memberList" :key="index">
				<view class="member-item" @click="chooseMember(index)">
					<view v-if="val.choose" class="ripple">
						<view style="--i:1"></view>
						<view style="--i:2"></view>
						<view style="--i:3"></view>
					</view>
					<!-- <image v-if="val.choose" class="choosebg" :src="$IMAGE_BASE_URL + '/img/new/memberChoose.png'"></image> -->
					<!-- <image class="img" :src="$IMAGE_BASE_URL + '/img/new/baba.png'"></image> -->
					<image v-if="val.avatarUrl" class="img" :src="val.avatarUrl"></image>
					<image v-else class="img" src="@/img/new/moren.png"></image>
					<view class="name" v-if="val.remark == null">{{val.nickName}}</view>
					<view class="name" v-else>{{val.remark}}</view>
					<view class="age">（{{val.age != null ? val.age : '--'}}岁）</view>
				</view>
			</block>
		</view>
		<view class="title">设备数量 ({{ deviceList.length }})</view>
		<view class="list">
			<view class="list-item" v-for="(item, index) in deviceList" :key="index">
				<view class="info">
					<view class="name">{{ item.name }}</view>
					<!-- <image class="edit" src="@/static/edit.png" @click="handleSetName(item)"></image> -->
				</view>
				<view v-if="isManager || isOwer" class="unbind" @click="onUnbind(item)">解绑</view>
			</view>
			<view v-if="isManager || isOwer" class="list-add" @click="toAddDevice">
				<image :src="$IMAGE_BASE_URL + '/static/ic_add.png'"></image>
			</view>
		</view>
		<!-- <empty v-if="!deviceList.length" :custom-style="{ padding: '180rpx 50rpx' }" tips="您当前没有设备~">
			<template v-slot:slot>
				<view class="empty-ipt" @click="onTargetIndex()">
					<text>去逛逛</text>
				</view>
			</template>
		</empty> -->
		<!-- 修改设备名称 -->
		<!-- <BaseModal :show="isNameShow" title="设备名称" :content="currentDevice.testName" type="input"
			@updateShow="e => isNameShow = e" @cancel="setNameCancel" @confirm="setNameConfirm" /> -->
		<!-- 解绑设备 -->
		<BaseModal :show="isUnbindShow" title="提示" content="解绑该设备吗？" @updateShow="e => isUnbindShow = e"
			@cancel="unbindCancel" @confirm="unbindConfirm" />
	</view>
</template>

<script>
	import BaseModal from "@/components/base-modal/index.vue";
	import Empty from '@/components/empty'
	import * as LoginApi from '@/api/login/index.js';
	import * as DeviceApi from "@/api/device/index.js";
	import {
		showInfo
	} from "@/utils/ToastUtils";
	import StorageUtils from "@/utils/StorageUtils";
	import CacheConfig from "@/config/CacheConfig";

	export default {
		data() {
			return {
				memberList: [],
				currentUuid: "",
				typeList: [],
				deviceList: [],
				currentDevice: {},
				isUnbindShow: false,
				isNameShow: false,
			};
		},
		components: {
			BaseModal,
			Empty
		},
		computed: {
			isManager() {
				const home = StorageUtils.get("home");
				const userInfo = StorageUtils.get(CacheConfig.USER_INFO_KEY);
				return home.userId == userInfo.id;
			},
			isOwer() {
				const member = this.memberList.find(v => v.choose == 1);
				const userInfo = StorageUtils.get(CacheConfig.USER_INFO_KEY);
				return !!member && member.id == userInfo.id;
			},
		},
		onLoad() {
			// const param = {
			// 	deviceName: "00:04:3E:4A:35:1B",
			// 	deviceType: "B_ECG",
			// 	uuid: "o7gmr7c26L0uGcpUcr3XnZ-Urkeg",
			// }
			// console.log('unbindConfirm param', param);
			// DeviceApi.bindDevice(param)
			this.init();
		},
		methods: {
			async init() {
				try {
					// 获取 homeId 和 userInfo
					const homeId = StorageUtils.get("homeId");
					const home = StorageUtils.get("home");
					const userInfo = StorageUtils.get(CacheConfig.USER_INFO_KEY);
					console.log("homeId", homeId);
					console.log("userInfo", userInfo);
					// 获取成员列表
					const membersRes = await LoginApi.homeMembers({
						homeId
					});
					const members = membersRes.obj;
					// 将当前用户移到首位
					// const currentUserIndex = members.findIndex(member => member.id === userInfo.id);
					// 将家庭管理者移到首位
					const currentUserIndex = members.findIndex(member => member.id === home.userId);
					if (currentUserIndex !== -1) {
						const currentUser = members.splice(currentUserIndex, 1)[0];
						members.unshift(currentUser);
					}
					// 初始化成员选择状态
					members.forEach((member, index) => {
						member.choose = (member.id == userInfo.id);
						this.currentUuid = member.uuid;
					});
					console.log("members", members);
					this.memberList = members;
					// 获取设备类型列表
					const deviceTypeRes = await LoginApi.getDeviceType();
					console.log("getDeviceType", deviceTypeRes);
					const deviceType = deviceTypeRes.obj;
					const typeList = Object.entries(deviceType).map(([key, value]) => ({
						value: key,
						label: value.msg
					}));
					this.typeList = typeList;
					// 获取设备列表
					await this.getDevice();
				} catch (err) {
					console.log("init error", err);
					showInfo(err.errMsg);
				}
			},
			chooseMember(index) {
				this.memberList.forEach((member, memberIndex) => {
					member.choose = memberIndex === index;
				});
				this.currentUuid = this.memberList[index].uuid;
				this.getDevice();
			},
			async getDevice() {
				try {
					const res = await LoginApi.device({
						uuid: this.currentUuid
					});
					console.log("getDevice success", res.obj);
					this.deviceList = res && res.obj ? res.obj.map(device => {
						const {
							label
						} = this.typeList.find(type => type.value === device.deviceType) || {};
						return {
							...device,
							name: device.deviceType == 'LIGHT' ? '医康网关' : label
						};
					}) : [];
				} catch (err) {
					console.log("getDevice error", err);
					showInfo(err.errMsg);
				}
			},
			toAddDevice() {
				this.$addDeviceService.scanCode(this.currentUuid);
			},
			handleSetName(item) {
				this.isNameShow = true;
				this.currentDevice = item;
			},
			setNameCancel() {
				this.currentDevice = {};
			},
			setNameConfirm() {
				console.log("修改名称");
				this.currentDevice = {};
			},
			onUnbind(item) {
				this.isUnbindShow = true;
				this.currentDevice = JSON.parse(JSON.stringify(item));
			},
			unbindCancel() {
				this.currentDevice = {};
			},
			unbindConfirm() {
				console.log("解绑", this.currentDevice);
				const param = {
					deviceName: this.currentDevice.deviceName,
					deviceType: this.currentDevice.deviceType,
					uuid: -1,
				};
				const option = {
					isPrompt: false,
				};
				console.log('unbindConfirm param', param);
				DeviceApi.bindDevice(param, option).then(res => {
					showInfo("解绑成功");
					const index = this.deviceList.findIndex(v => v.id == this.currentDevice.id);
					this.deviceList.splice(index, 1);
					if(err.errMsg == 'Device is offline') {
						showInfo("解绑失败：星梦云康离线");
					}else if(err.errMsg == '超时') {
						showInfo("解绑失败：发送指令超时");
					}
				})
			}
		}
	}
</script>

<style lang="scss" scoped>
	.device {
		height: 100vh;
		background-color: #f5f5f7;

		.member-list {
			display: flex;
			flex-wrap: wrap;
			padding: 40rpx 40rpx 0 40rpx;
			background-color: #FFFFFF;
			display: flex;
			margin-top: 1rpx;

			.member-item {
				width: 25%;
				display: flex;
				flex-direction: column;
				align-items: center;
				position: relative;
				z-index: 1;
				margin-bottom: 20rpx;

				.ripple {
					position: absolute;
					top: -5rpx;
					left: 50%;
					transform: translateX(-50%);
					z-index: -1;
					display: flex;
					justify-content: center;
					align-items: center;
					width: 130rpx;
					height: 130rpx;

					view {
						position: absolute;
						background: #81d3b7;
						box-sizing: border-box;
						border-radius: 100%;
						animation: animate 1s linear infinite;
						animation-delay: calc(0.5s * var(--i));
					}
				}

				.choosebg {
					width: 130rpx;
					height: 130rpx;
					position: absolute;
					z-index: -1;
					top: -1rpx;
					margin: auto;
					display: block;
					left: calc(50% - 66rpx);
				}

				.img {
					width: 92rpx;
					height: 92rpx;
					border-radius: 100%;
					margin: 17rpx auto;
					display: block;
				}

				.name {
					font-size: 30rpx;
					margin-top: 20rpx;
				}

				.age {
					font-size: 24rpx;
				}

			}

		}

		.title {
			font-family: SourceHanSansCN;
			font-size: 36rpx;
			font-weight: bold;
			color: #2b2a2e;
			margin-top: 20rpx;
			margin-bottom: 33rpx;
			margin-left: 7rpx;
			padding: 0 26rpx;
		}

		.list {
			display: flex;
			justify-content: space-between;
			flex-wrap: wrap;
			padding: 0 26rpx;

			.list-item {
				width: 331rpx;
				height: 182rpx;
				background-color: #FFFFFF;
				border-radius: 20rpx;
				display: flex;
				flex-direction: column;
				align-items: flex-end;
				justify-content: space-between;
				padding: 27rpx 23rpx 15rpx 23rpx;
				box-sizing: border-box;
				margin-bottom: 38rpx;
				box-shadow: 0 0 20rpx rgba(0, 0, 0, 0.1);

				.info {
					display: flex;
					align-items: center;
					width: 100%;

					.name {
						font-family: SourceHanSansCN;
						font-size: 36rpx;
						font-weight: bold;
						color: #616162;
					}

					.edit {
						width: 30rpx;
						height: 30rpx;
						margin-left: 15rpx;
					}
				}

				.unbind {
					font-family: SourceHanSansCN;
					font-size: 24rpx;
					color: #fd7349;
					padding: 5rpx 20rpx;
					border-radius: 20rpx;
					background-color: #FFFFFF;
					border: 1rpx solid #fd7349;
				}

			}

			.list-add {
				width: 331rpx;
				height: 182rpx;
				background-color: #FFFFFF;
				border-radius: 20rpx;
				display: flex;
				align-items: center;
				justify-content: center;
				box-shadow: 0 0 20rpx rgba(0, 0, 0, 0.1);

				image {
					width: 44rpx;
					height: 44rpx;
				}
			}
		}

		// 空数据按钮
		.empty-ipt {
			margin: 0 auto;
			width: 250rpx;
			height: 70rpx;
			font-size: 32rpx;
			text-align: center;
			color: #fff;
			border-radius: 50rpx;
			background: linear-gradient(to right, $main-bg, $main-bg2);
			color: $main-text;
			display: flex;
			justify-content: center;
			align-items: center;
		}
	}

	@keyframes animate {
		0% {
			opacity: 0;
		}

		10% {
			width: 100rpx;
			height: 100rpx;
			opacity: 0.5;
		}

		50% {
			opacity: 0.5;
		}

		100% {
			width: 160rpx;
			height: 160rpx;
			opacity: 0;
		}
	}
</style>